package com.hengtongxing.hejiayun.homepage;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseActivity;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.AddressListBean;
import com.hengtongxing.hejiayun.bean.ImageBean;
import com.hengtongxing.hejiayun.bean.OrderDetailsBean;
import com.hengtongxing.hejiayun.bean.OrderListBean;
import com.hengtongxing.hejiayun.bean.PrepareConfigBean;
import com.hengtongxing.hejiayun.bean.RefundAmountBean;
import com.hengtongxing.hejiayun.bean.RefundBean;
import com.hengtongxing.hejiayun.homepage.model.HomePageModelImpl;
import com.hengtongxing.hejiayun.homepage.model.IHomePageModel;
import com.hengtongxing.hejiayun.mine.model.IMineModel;
import com.hengtongxing.hejiayun.mine.model.MineModelImpl;
import com.hengtongxing.hejiayun.shop.adapter.Adapter_PictureSelector;

import com.hengtongxing.hejiayun.utils.Base64BitmapUtil;
import com.hengtongxing.hejiayun.utils.GlideEngine;
import com.hengtongxing.hejiayun.utils.GlideUtils;
import com.hengtongxing.hejiayun.utils.PermissionsManager;
import com.hengtongxing.hejiayun.widget.AppTitleBar;
import com.hengtongxing.hejiayun.widget.FullyGridLayoutManager;
import com.hengtongxing.hejiayun.widget.ViewLoading;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.ArrayList;
import java.util.List;

public class ApplyForRefundActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.iv_goods_thumb)
    RoundedImageView ivGoodsThumb;
    @BindView(R.id.tv_goods_name)
    TextView tv_goods_name;
    @BindView(R.id.tv_goods_norm)
    TextView tv_goods_norm;
    @BindView(R.id.tv_goods_price)
    TextView tv_goods_price;
    @BindView(R.id.tv_goods_num)
    TextView tv_goods_num;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rl_cargo_status)
    RelativeLayout rl_cargo_status;
    @BindView(R.id.rl_reason_for_refund)
    RelativeLayout rl_reason_for_refund;

    @BindView(R.id.tv_cargo_status)
    TextView tv_cargo_status;
    @BindView(R.id.tv_reason_for_refund)
    TextView tv_reason_for_refund;
    @BindView(R.id.tv_refund_amount)
    TextView tv_refund_amount;
    @BindView(R.id.edit_info)
    EditText edit_info;
    @BindView(R.id.tv_commit)
    TextView tv_commit;
    private PermissionsManager permissionsManager;
    private List<String> imgList = new ArrayList<>();
    private Adapter_PictureSelector adapter;
    private BottomSheetDialog selectPicDialog;
    private int openType;//0 相册，1相机
    private String[] permissions;
    private int id;
    private IMineModel mineModel;
    private IHomePageModel homePageModel;
    private String refund_amount;
    private String type;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_for_refund);
        ButterKnife.bind(this);
        mineModel = new MineModelImpl();
        homePageModel = new HomePageModelImpl();
        initView();
        initData();
        initEvent();
    }


    private void initView() {
        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        type = intent.getStringExtra("type");
        String shop_goods_thumb = intent.getStringExtra("shop_goods_thumb");
        String shop_goods_name = intent.getStringExtra("shop_goods_name");
        String norm_name = intent.getStringExtra("norm_name");
        String shop_goods_price = intent.getStringExtra("shop_goods_price");
        String count = intent.getStringExtra("count");

        if ("0".equals(type)) {
            titleBar.setTitle("退款");
        } else if ("1".equals(type)) {
            titleBar.setTitle("退款退货");
            rl_cargo_status.setVisibility(View.GONE);
        }
        GlideUtils.loadImage(this, ivGoodsThumb, shop_goods_thumb);
        tv_goods_name.setText(shop_goods_name);
        tv_goods_norm.setText(norm_name);
        tv_goods_price.setText(shop_goods_price);
        tv_goods_num.setText(count);


        permissionsManager = new PermissionsManager(this);
        FullyGridLayoutManager fullyGridLayoutManager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(fullyGridLayoutManager);

        adapter = new Adapter_PictureSelector(this);
        adapter.setImgList(imgList);
        recyclerView.setAdapter(adapter);
        adapter.setOnAddPicClickListener(this::showPictureSelectorDialog);
        adapter.setOnItemClickListener(this::handlerAdapterItemClick);

    }

    private void initData() {

        mineModel.returnGoodsMoney(id, new DataCallBack<RefundAmountBean>() {
            @Override
            public void onSuccessful(RefundAmountBean bean) {
                refund_amount = bean.getData().getRefund_amount();
                tv_refund_amount.setText("¥" + Double.valueOf(refund_amount)/100);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void initEvent() {
        rl_cargo_status.setOnClickListener(v -> {
            //货物状态
            showCargoStatusDialog();
        });
        rl_reason_for_refund.setOnClickListener(v -> {
            //退款原因
            showReasonForRefundDialog();
        });

        tv_commit.setOnClickListener(v -> {
            returnGoods();
        });
    }


    private void returnGoods() {
//        申请退货退款 ShopOrder/returnGoods
//        参数 order_goods_id
//        goods_status 货物状态 1 未收到货 2已收到货
//        remark 退款原因
//        refund_amount 退款金额
//        delivery_no 快递单号(非必填)
//                depict 描述(非必填)
//        pic 凭证图片 json数组类型 (非必填)
        String cargo_status = tv_cargo_status.getText().toString().trim();

        if ("0".equals(type)) {
            if ("请选择".equals(cargo_status)) {
                Toast.makeText(mActivity, "请选择货物状态", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        String reason_for_refund = tv_reason_for_refund.getText().toString().trim();
        String depict = edit_info.getText().toString().trim();
        if ("请选择".equals(reason_for_refund)) {
            Toast.makeText(mActivity, "请选择退款原因", Toast.LENGTH_SHORT).show();
            return;
        }

        String goods_status = "";
        if ("未收到货".equals(cargo_status)) {
            goods_status = "1";
        } else if ("已收到货".equals(cargo_status)) {
            goods_status = "2";
        }

        mineModel.returnGoods(id, goods_status, reason_for_refund, refund_amount, "", depict, imgList, new DataCallBack<RefundBean>() {
            @Override
            public void onSuccessful(RefundBean bean) {
                Toast.makeText(mActivity, bean.getData(), Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showCargoStatusDialog() {

        BottomSheetDialog selectPicDialog = new BottomSheetDialog(this, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_reason_for_refund, null);
        //未收到货
        TextView tv_goods_not_received = view.findViewById(R.id.tv_goods_not_received);
        //已收到货
        TextView tv_received_goods = view.findViewById(R.id.tv_received_goods);
        //取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        tv_goods_not_received.setOnClickListener(v -> {
            tv_cargo_status.setText("未收到货");
            selectPicDialog.dismiss();
        });
        tv_received_goods.setOnClickListener(v -> {
            tv_cargo_status.setText("已收到货");
            selectPicDialog.dismiss();
        });
        cancel.setOnClickListener(v -> {
            selectPicDialog.dismiss();
        });

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    private void showReasonForRefundDialog() {

        BottomSheetDialog selectPicDialog = new BottomSheetDialog(this, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_after_sale, null);
        //取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);
        TextView tv_sizi_no = view.findViewById(R.id.tv_sizi_no);
        TextView tv_color_pattern_style_no = view.findViewById(R.id.tv_color_pattern_style_no);
        TextView tv_texture_material_no = view.findViewById(R.id.tv_texture_material_no);
        TextView tv_work_no = view.findViewById(R.id.tv_work_no);
        TextView tv_quality_no = view.findViewById(R.id.tv_quality_no);

        tv_sizi_no.setOnClickListener(v -> {
            //大小/尺寸与商品描述不符
            tv_reason_for_refund.setText("大小/尺寸与商品描述不符");
            selectPicDialog.dismiss();
        });
        tv_color_pattern_style_no.setOnClickListener(v -> {
            //颜色/图案/款式与商品描述不符
            tv_reason_for_refund.setText("颜色/图案/款式与商品描述不符");
            selectPicDialog.dismiss();
        });
        tv_texture_material_no.setOnClickListener(v -> {
            //材质与商品描述不符
            tv_reason_for_refund.setText("材质与商品描述不符");
            selectPicDialog.dismiss();
        });
        tv_work_no.setOnClickListener(v -> {
            //做工粗糙/有瑕疵
            tv_reason_for_refund.setText("做工粗糙/有瑕疵");
            selectPicDialog.dismiss();
        });
        tv_quality_no.setOnClickListener(v -> {
            //质量问题
            tv_reason_for_refund.setText("质量问题");
            selectPicDialog.dismiss();
        });
        cancel.setOnClickListener(v -> {
            selectPicDialog.dismiss();
        });

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }


    private void showPictureSelectorDialog() {
        if (imgList.size() >= 3) {
            Toast.makeText(mActivity, "最多选择三张图片", Toast.LENGTH_SHORT).show();
            return;
        }


        selectPicDialog = new BottomSheetDialog(this, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    private void handlerAdapterItemClick(int position, View v) {

//        List<LocalMedia> selectList = adapter.getMediaList();

//        if (selectList != null && selectList.size() > 0) {
//            PictureSelector.create(this).externalPicturePreview(position, selectList, 0);
//        }
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }


    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(mActivity)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(new ArrayList<>())//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(mActivity)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(new ArrayList<>())//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                if (isDestroy()) {
                    return;
                }
                List<LocalMedia> list = new ArrayList<>();
                LocalMedia localMedia = new LocalMedia();
                localMedia.setPath(bean.getData().getUrl());
                list.add(localMedia);
                adapter.addMediaList(list);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }
    }
}